<template>
    <div>
        <div id="allmap" style="display:none;">
        </div>
    </div>
</template>
<script>
import axios from 'axios';
export default {
    data () {
        return {
            polygonList: [],
            parallelArray: [],
        }
    },
    components:{
        
    },
    computed:{
        
    },
    created() {
        
    },
    mounted(){
        this.initScript()
    },
    methods: {
        initScript() {
			//判断如果有script就删掉
			if (document.querySelector("#amap-box")){
				this.initMap();
			}else{
                let amapBox = document.createElement("div");
                amapBox.setAttribute("id", "amap-box");
                let script1 = document.createElement("script");
                script1.onload = () => {
                    let script2 = document.createElement("script");
                    script2.onload = () => {
                        this.initMap();
                    }
                    script2.src = "//webapi.amap.com/ui/1.0/main.js";
                    amapBox.insertAdjacentElement("beforeend", script2);
                };
                script1.src = "http://webapi.amap.com/maps?v=1.3&key=9bfe3d8b8882b7d3e4c23e43d38b18ba";
                amapBox.insertAdjacentElement("beforeend", script1);
                document.body.appendChild(amapBox);
            }
        },
        getStoreList() {
            let url = api.base_host + "/baseStore/getRestStore";
            let options = {
                url,
                methods: "GET",
            };
            return axios(options);
        },
        initMap(){
			var that = this;
			var shop;
			var kmReg = /\d+km/;
			//所有marker的集合，用于地图自适应缩放
			var markerList = [];
			var tenSecond = false;
			var tenTimer;
			var shopLng = Number(localStorage.getItem("storeLng")) || 108.396208;
			var shopLat = Number(localStorage.getItem("storeLat")) || 22.811724;
			shop = createShopObject(shopLng, shopLat, "门店位置", 5000);
			//工厂模式，生成门店对象
			function createShopObject(lon, lat, name, radius) {
				var obj = {
					lon : lon,
					lat : lat,
					name : name,
					radius : radius
				}
				return obj;
			}
			//基础接口地址
			function getBaseUrl(){
				return "http://test.njxs.weilian.cn/";
			}

            //高德地图
            var map = new AMap.Map('allmap', {
                resizeEnable: true,
                zoom: 15,
                center: [108.383765, 22.813923],
                scrollWheel : true
            });
			//定位功能
			map.plugin(['AMap.Geolocation', 'AMap.Autocomplete', "AMap.Geocoder"], function() {
				//给一个定位过程的loading
				var geolocation = new AMap.Geolocation({
					enableHighAccuracy: true, //是否使用高精度定位，默认:true
					timeout: 5000, //超过10秒后停止定位，默认：无穷大
					maximumAge: 0, //定位结果缓存0毫秒，默认：0
					convert: true, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
					showButton: true, //显示定位按钮，默认：true
					buttonPosition: 'RB', //定位按钮停靠位置，默认：'LB'，左下角
					buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
					showMarker: false, //定位成功后在定位到的位置显示点标记，默认：true
					showCircle: false, //定位成功后用圆圈表示定位精度范围，默认：true
					panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
					zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false,
				});
				//个人定位的marker
				var mineMarker = new AMap.Marker({
					icon: "http://webapi.amap.com/theme/v1.3/markers/b/loc.png",
					label : {
						offset: new AMap.Pixel(34, 17),//修改label相对于maker的位置
						content: "您的位置"
					}
				});
				// map.addControl(geolocation);
				// setTimeout(function () {
				geolocation.getCurrentPosition();
				// }, 5000);
				
				//添加定位失败和定位成功的监听事件
				geolocation.on("complete", async function (result) {
                    console.log(result,'location');
                    console.log(that.polygonList,'polygonList');
                    console.log(that.parallelArray,'parallelArray');
                    let index;
                    let lnglat = new AMap.LngLat(result.position.lng, result.position.lat);
                    that.polygonList.map((ele,ind) => {
                        ele.contains(lnglat) ? index = ind : '';
                    })
                    index ? console.log(index) : console.log('不在范围内');
                    let temp = await that.getStoreList();
                    let storeList = temp.data.data[0];
                    console.log(storeList,'StoreList')
                    storeList.map((ele,ind) => {
                        ele.distance = calculate(ele.positionLat, ele.positionLng, result.position.lat, result.position.lng);
                    })
                    console.log(storeList,'has distance');
				});
				geolocation.on("error", function () {
					console.log('定位失败')
				});

				var geocoder = new AMap.Geocoder({
					city: "010"//城市，默认：“全国”
				});
	
				/*根据经纬度计算距离，单位是千米*/
				function calculate(lat1, lng1, lat2, lng2) {
					var radLat1 = lat1 * Math.PI / 180.0;
					var radLat2 = lat2 * Math.PI / 180.0;
					var a = radLat1 - radLat2;
					var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
					var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
					s = s * 6378.137;
					s = Math.round(s * 10000) / 10000;
					return s
				};
				/*给出结果*/
				function end(param1, param2) {
					var result = [];
					for(var i in param1) {
						for(var j in param2) {
							if(calculate(param1[i].lat, param1[i].lng, param2[j].lat, param2[j].lng) < param2[j].long) {
								result.push(i);
							}
						}
					}
					return result;
				}
			});
			//门店marker 将当前门店显示在地图上
			(function () {
				var isShow = false;
				if(document.querySelector("#search-input")){
                    document.querySelector("#search-input").onkeyup = function(){
                        this.value == "" ? that.positionList = [] : "";
                    }
                }
				//请求配送范围的经纬度数组
				// let url = "http://172.19.5.89:33004/address/getTMS";
				let url = api.customer_host + "/address/getTMS";
				axios.get(url,{
						"longitudeandlatitude":""
					})
					.then(function (res) {
						that.polygonList = [];
						//门店配送范围
                        let array = new Array();
                        let replica = new Array();
                        console.log(res.data.data[0],'shopList')
						for(let item of res.data.data[0]){
							let Arr = new Array();
							for(let it of JSON.parse(item.longitudeandlatitude)){
								let arr = new Array();
								arr[0] = it.a;
                                arr[1] = it.b;
								Arr.push(arr);
							}
                            // item.deptid == localStorage.getItem("storeId") && array.push(Arr);
                            array.push(Arr);
                            replica.push(item);
                        }
                        that.parallelArray = replica;
                        console.log(array,'array')
                        console.log(that.parallelArray,'parallelArray')
						//多边形覆盖物节点坐标数组
						for (let item of array){
							var polygon = new AMap.Polygon({
								map: map,
								path: item,//设置多边形边界路径
								strokeColor: "red", //线颜色
								strokeOpacity: 0.2, //线透明度
								strokeWeight: 3,    //线宽
								fillColor: "red", //填充色
                                fillOpacity: 0.35//填充透明度
							});
							polygon.setMap(map);
							that.polygonList.push(polygon);
						}
						console.log(that.polygonList,"polygonList")
					})
					.catch(function (res) {
						//console.log(res);
					});
				//将门店配送范围显示在地图上
				var shopMarker = new AMap.Marker({
					// icon: "static/image/ning_store.png",
					position: [shop.lon, shop.lat],
					 icon: new AMap.Icon({            
						size: new AMap.Size(48, 48),  //图标大小
						image: "static/image/ning_store.png",
						imageSize: new AMap.Size(48,48),
						imageOffset: new AMap.Pixel(0, 0)
					}),        
					label : {
						offset: new AMap.Pixel(37, 28),//修改label相对于maker的位置
						content: shop.name
					}
				});
				markerList.push(shopMarker);
				shopMarker.setMap(map);
			})();
		},
    }
}
</script>
<style scoped>

</style>